package com.example.music.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.example.music.R
import com.example.music.adapter.BannerAdapter
import com.example.music.adapter.InfiniteBannerAdapter
import com.example.music.adapter.SongAdapter
import com.example.music.network.MusicApi
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

class RecommendFragment : Fragment() {
    private lateinit var musicApi: MusicApi
    private lateinit var bannerAdapter: BannerAdapter
    private lateinit var infiniteBannerAdapter: InfiniteBannerAdapter
    private lateinit var songAdapter: SongAdapter
    private lateinit var viewPager: ViewPager2
    
    private val handler = Handler(Looper.getMainLooper())
    private val autoScrollRunnable = object : Runnable {
        override fun run() {
            viewPager.currentItem = viewPager.currentItem + 1
            handler.postDelayed(this, 3000)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_recommend, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupAdapters(view)
        setupRetrofit()
        loadData()
    }

    override fun onResume() {
        super.onResume()
        handler.postDelayed(autoScrollRunnable, 3000)
    }

    override fun onPause() {
        super.onPause()
        handler.removeCallbacks(autoScrollRunnable)
    }

    private fun setupAdapters(view: View) {
        // Banner ViewPager
        bannerAdapter = BannerAdapter()
        infiniteBannerAdapter = InfiniteBannerAdapter(bannerAdapter)
        viewPager = view.findViewById<ViewPager2>(R.id.bannerViewPager).apply {
            adapter = infiniteBannerAdapter
            setPageTransformer { page, position ->
                val absPosition = kotlin.math.abs(position)
                page.alpha = 1f - (absPosition * 0.5f)
                page.scaleX = 0.85f + (1f - absPosition) * 0.15f
                page.scaleY = page.scaleX
            }
        }

        // Recommendations RecyclerView
        songAdapter = SongAdapter()
        view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.recommendationsRecyclerView).apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
            adapter = songAdapter
        }
    }

    private fun setupRetrofit() {
        val client = OkHttpClient.Builder()
            .addInterceptor(HttpLoggingInterceptor().apply { 
                level = HttpLoggingInterceptor.Level.BASIC 
            })
            .connectTimeout(15, TimeUnit.SECONDS)
            .build()

        musicApi = Retrofit.Builder()
            .baseUrl("http://121.37.40.55:3000/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(MusicApi::class.java)
    }

    private fun loadData() {
        lifecycleScope.launch {
            try {
                musicApi.getBanners().let { banners ->
                    if (banners.isNotEmpty()) {
                        infiniteBannerAdapter.submitList(banners)
                        viewPager.setCurrentItem(Int.MAX_VALUE / 2, false)
                    }
                }
                
                songAdapter.submitList(musicApi.getRecommendations())
            } catch (e: Exception) {
                Log.e("RecommendFragment", "加载失败", e)
                Toast.makeText(requireContext(), "加载失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(autoScrollRunnable)
    }
} 